package com.binance.rabbitmq.config;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Singular;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Created by robin.wu on 2018/11/30.
 */
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Log4j2
@ConfigurationProperties
public class DelayConfig extends AbstractConfig {

    @NestedConfigurationProperty
    private ExchangeConfig delayExchange;

    @Singular
    private Map<String,QueueConfig> queues;

    private String routingKey;


    @Override
    public boolean validate() {
        log.info("Validating DelayConfig...");
        boolean valid;
        if (delayExchange == null) {
            log.error("Validating failed. DelayExchange must provided for delay config.");
            valid = false;
        }else {
            valid = delayExchange.validate();
        }

        if(StringUtils.isEmpty(routingKey)) {
            log.error("Validating failed. Delay routing key must provided for delay config");
        }

        log.info("Validating delay queue...");
        for (Map.Entry<String, QueueConfig> entry : queues.entrySet()) {
            valid = validate(entry.getKey(), entry.getValue(), valid);
        }

        return valid;
    }

    private boolean validate(String key, QueueConfig queueConfig, boolean valid) {
        log.info("Validating key {} :: value {}...", key, queueConfig);

        if(queueConfig.getDelayMillisecond() == null) {
            return false;
        }

        return queueConfig.validate() ? valid : false;
    }
}
